/**
 * 微博超话自动签到插件 V1.6.1
 * Created by MapleX
 * background.js - 后台服务脚本
 */

// 获取下一次签到时间
function getNextNoonTime() {
  return new Promise((resolve) => {
    chrome.storage.local.get(['autoCheckEnabled', 'autoCheckInTime'], (result) => {
      if (!result.autoCheckEnabled) {
        resolve(null);
        return;
      }

      const now = new Date();
      const next = new Date(now);
      
      const [hours, minutes] = (result.autoCheckInTime || '12:00').split(':');
      next.setHours(parseInt(hours), parseInt(minutes), 0, 0);
      
      if (now >= next) {
        next.setDate(next.getDate() + 1);
      }
      
      resolve(next.getTime());
    });
  });
}

// 设置定时任务
async function setupDailyAlarm() {
  const nextTime = await getNextNoonTime();
  if (nextTime) {
    chrome.alarms.create('dailyCheckIn', {
      when: nextTime,
      periodInMinutes: 24 * 60
    });
  }
}

// 更新定时任务
async function updateAlarm() {
  // 先清除现有的定时任务
  await chrome.alarms.clear('dailyCheckIn');
  // 重新设置定时任务
  await setupDailyAlarm();
}

// 处理定时任务
chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === 'dailyCheckIn') {
    chrome.storage.local.get(['savedTopics'], (result) => {
      const topics = result.savedTopics || [];
      if (topics.length > 0) {
        startCheckInProcess(topics);
      }
    });
  }
});

// 监听来自content script和popup的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'processSuperTopics' && message.urls) {
    processSuperTopics(message.urls, sender.tab.id);
  } else if (message.action === 'startCheckIn') {
    startCheckInProcess(message.topics);
  } else if (message.action === 'updateAutoCheck') {
    updateAutoCheck(message.enabled, message.time);
  } else if (message.action === 'stopCheckIn') {
    isCheckingIn = false;
    // 如果有当前签到窗口，立即关闭它
    if (currentCheckInWindowId) {
      chrome.windows.remove(currentCheckInWindowId);
      currentCheckInWindowId = null;
    }
    // 更新状态
    chrome.storage.local.set({ 
      status: '签到已停止',
      isCheckingIn: false
    });
  }
});

// 开始签到流程
function startCheckInProcess(topics) {
  chrome.storage.local.set({ 
    status: '准备开始签到...'
  });

  const urls = topics.map(topicId => 
    `https://weibo.com/p/${topicId}/super_index`
  );
  
  processSuperTopics(urls);
}

// 添加一个变量来跟踪签到状态
let isCheckingIn = false;

// 添加一个变量来保存当前签到窗口的ID
let currentCheckInWindowId = null;

// 处理超话签到
async function processSuperTopics(urls, originalTabId) {
  try {
    isCheckingIn = true;
    chrome.storage.local.set({ 
      status: `找到 ${urls.length} 个超话，开始签到...`,
      isCheckingIn: true
    });

    // 将 URLs 分成小批次处理，每批 15 个
    const batchSize = 15;
    const batches = [];
    for (let i = 0; i < urls.length; i += batchSize) {
      batches.push(urls.slice(i, i + batchSize));
    }

    // 逐批处理
    for (let i = 0; i < batches.length; i++) {
      // 如果停止标志被设置，则退出处理
      if (!isCheckingIn) {
        if (currentCheckInWindowId) {
          try {
            await chrome.windows.remove(currentCheckInWindowId);
          } catch (error) {
            console.error('关闭窗口失败:', error);
          }
          currentCheckInWindowId = null;
        }
        chrome.storage.local.set({ 
          status: '签到已停止'
        });
        return;
      }

      const batchUrls = batches[i];
      const batchNumber = i + 1;
      
      chrome.storage.local.set({ 
        status: `正在处理第 ${batchNumber}/${batches.length} 批超话...`
      });

      try {
        // 创建一个隐藏的窗口
        const window = await chrome.windows.create({
          url: batchUrls,
          state: 'normal',
          focused: false,
          width: 1,
          height: 1,
          left: -10000,
          top: -10000
        });

        // 然后尝试最小化窗口
        try {
          await chrome.windows.update(window.id, { state: 'minimized' });
        } catch (error) {
          console.error('窗口最小化失败:', error);
        }

        // 保存当前窗口ID
        currentCheckInWindowId = window.id;

        // 等待这一批次的处理完成
        await new Promise(resolve => {
          setTimeout(async () => {
            try {
              // 获取窗口中的所有标签页
              const tabs = await chrome.tabs.query({ windowId: window.id });
              
              // 向所有标签页发送签到消息并等待结果
              const checkInPromises = tabs.map(tab => 
                new Promise(async (tabResolve) => {
                  try {
                    const response = await new Promise((msgResolve) => {
                      chrome.tabs.sendMessage(tab.id, { action: 'checkIn' }, (result) => {
                        msgResolve(result);
                      });
                    });
                    
                    if (response && response.success) {
                      try {
                        await chrome.tabs.remove(tab.id);
                      } catch (error) {
                        console.error('标签页关闭失败:', error);
                      }
                    }
                  } catch (error) {
                    console.error('标签页处理失败:', error);
                  }
                  tabResolve();
                })
              );

              // 等待所有标签页处理完成
              await Promise.all(checkInPromises);

              // 关闭窗口
              try {
                if (currentCheckInWindowId === window.id) {
                  await chrome.windows.remove(window.id);
                  currentCheckInWindowId = null;
                }
              } catch (error) {
                console.error('窗口关闭失败:', error);
              }
            } catch (error) {
              console.error('批次处理失败:', error);
            }
            resolve();
          }, 5000);
        });
      } catch (error) {
        console.error('窗口创建失败:', error);
      }
    }

    // 所有批次处理完成
    if (originalTabId) {
      try {
        await chrome.tabs.remove(originalTabId);
      } catch (error) {
        console.error('原始标签页关闭失败:', error);
      }
    }
    
    isCheckingIn = false;
    currentCheckInWindowId = null;
    
    // 更新所有状态
    chrome.storage.local.set({ 
      status: '所有超话签到完成！',
      isCheckingIn: false  // 清除运行状态
    });
  } catch (error) {
    console.error('签到过程出错:', error);
    // 确保错误时也清除状态
    isCheckingIn = false;
    currentCheckInWindowId = null;
    chrome.storage.local.set({ 
      status: '签到过程出错！',
      isCheckingIn: false
    });
  }
}

// 更新自动签到设置
async function updateAutoCheck(enabled, time) {
  // 先清除现有的定时任务
  await chrome.alarms.clear('dailyCheckIn');
  
  if (enabled) {
    // 重新设置定时任务
    await setupDailyAlarm();
  }
}

chrome.runtime.onInstalled.addListener(() => {
  setupDailyAlarm();
});

chrome.runtime.onStartup.addListener(() => {
  setupDailyAlarm();
}); 